library main;

import 'dart:io';
import 'dart:convert';
import 'dart:collection';

part 'types.dart';

void main() {
   Delivery first;
   Queue<Delivery> latest = new Queue<Delivery>();

   // every minute
   Queue<Delivery> delivs = new Queue<Delivery>();

   // make list of all new balls received from cricinfo
   String enc = new File('temp/temp.json').readAsStringSync();
   Map dec = JSON.decode(enc);
   List overs = dec['comms'];
   for (var over in overs) {
      List balls = over['ball'];
      for (var ball in balls) delivs.addFirst(new Delivery(ball));
   }

   // merge the balls in this list with those in queue
   for (var deliv in delivs) {
      if (latest.contains(deliv)) {
         bool test (Delivery any) => any == deliv;
         Delivery inner = latest.singleWhere(test);
         if (inner.moreData(deliv)) inner.update(deliv);
         else inner.count++;
      }
      else latest.addLast(deliv);
   }

   // dispatch balls that are complete/stable
   num length = latest.length;
   for (var i = 0; i < length; i++) {
      if (latest.first.count >= 2) dispatch(latest.removeFirst());
      else break;
   }

   // reset and sanity check
   first = latest.first;
   assert(delivs.contains(first));
   print(first);
   print(delivs.length);
}

void dispatch (Delivery ready) {
   print('dispatched ball ${ready.id}');
}
